<?php

// +----------------------------------------------------------------------
// | API日志模型
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;
use \think\Response;

class Apilog extends Model
{
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;

    /**
     * 记录api日志
     */
    public function record(Response $response)
    {
        $module = request()->module();
        $controller = request()->controller();
        $action = request()->action();
        $params = request()->param();
        $app_route = $module.'/'.$controller.'/'.$action;

        // 后台的操作不记录, 排除一些模块不记录, 不是返回json的页面不记录, ajax不记录
        if( in_array(strtolower($module), ['admin', 'common', 'addons', 'cms', 'error'])
            || empty($response->getHeader('Content-Type'))
            || strpos($response->getHeader('Content-Type'), 'json') === false
            /*|| request()->isAjax()*/
        ) {
            return;
        }
        $uri = input('server.REQUEST_URI');
        $isSuccess = 0;
        $param = input('post.');
        $content = $response->getContent();
        if($response->getCode()=='200') {
            if(!empty($content)) {
                $arr = json_decode($content, JSON_UNESCAPED_UNICODE);
                if($arr && isset($arr['code']) && $arr['code']==1) {
                    $isSuccess = 1;
                }
            }
        }
        $uid = (int) cookie('uid');
        $data = [
            'url' => $uri,
            'app_route' => $app_route,
            'request_param' => json_encode($param),
            'request_method' => request()->method(),
            'request_content_type' => request()->contentType(),
            'request_ip' => request()->ip(),
            'http_user_agent' => request()->server('HTTP_USER_AGENT'),
            'response_text' => $content,
            'response_content_type' => $response->getHeader('Content-Type'),
            'response_code' => $response->getCode(),
            'is_success' => $isSuccess,
            'uid' => $uid,
            'create_time' => time(),
            'server' => request()->server(),
        ];
        \think\facade\Log::record($data, 'request_info');

        $this->allowField(true)->data($data)->save();
    }

}
